package com.chs.recoginition.vo;

import com.chs.recoginition.core.config.WebConfig;
import com.chs.recoginition.core.exception.ApplicationException;
import com.chs.recoginition.core.exception.constant.ExceptionConstant;
import com.chs.recoginition.core.utils.LocalDateTimeUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

@Slf4j
@Component("jwtResource")
public class JwtResource {

    @Resource
    private WebConfig webConfig;

    /**
     * 生成token
     */
    public String generateToken(Map<String, Object> tokenDataMap) {
        return Jwts.builder()
                .setClaims(tokenDataMap)
                .setIssuedAt(new Date())
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, webConfig.getJwtSecret())
                .compact();
    }

    /**
     * 校验token
     */
    public boolean validateToken(String token, String username) {
        String usernameByToken = getUsernameByToken(token);

        return Objects.equals(usernameByToken, username) && !isTokenExpired(token);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            final Claims claims = getClaimsFromToken(token);
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * token是否可以刷新（token有效时间过半则可以刷新）
     */
    public boolean canTokenBeRefreshed(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            Date halfDate = LocalDateTimeUtils.getHalfDate(claims.getIssuedAt(), claims.getExpiration());
            return halfDate.getTime() < System.currentTimeMillis();
        }
        return false;
    }

    /**
     * 获取token的数据
     */
    public Map<String, Object> getDataByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(webConfig.getJwtSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据token获取用户名
     * @param token
     * @return
     */
    public String getUsernameByToken(String token) {
        Map<String, Object> data = getDataByToken(token);
        if (data != null && data.get(webConfig.getJwtUsernameKey()) != null) {
            return String.valueOf(data.get(webConfig.getJwtUsernameKey()));
        }
        return null;
    }

    /**
     * 根据token获取用户姓名
     * @param token
     * @return
     */
    public String getNameByToken(String token) {
        Map<String, Object> data = getDataByToken(token);
        if (data != null && data.get(webConfig.getJwtNameKey()) != null) {
            return String.valueOf(data.get(webConfig.getJwtNameKey()));
        }
        return null;
    }

    /**
     * 根据token获取用户信息对象
     */
    public LinkedHashMap getUserVoByToken(String token) {
        Map<String, Object> data = getDataByToken(token);
        if (data != null && data.get(webConfig.getJwtUserVo()) != null) {
            return (LinkedHashMap) data.get(webConfig.getJwtUserVo());
        }
        return null;
    }

    /**
     * 获取token过期时间
     */
    public Date getExpirationDateByToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    /**
     * 验证token并添加data到attribute，验证不通过会抛出 UNAUTHORIZED
     */
    public HttpServletRequest validateTokenAddDataToAttr(HttpServletRequest request) {
        String token = getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new ApplicationException(ExceptionConstant.UNAUTHORIZED);
        }

        try {
            Map<String, Object> data = this.getDataByToken(token);
            for (String key : data.keySet()) {
                request.setAttribute(key, data.get(key));
            }
            return request;
        } catch (Exception e) {
            throw new ApplicationException(ExceptionConstant.UNAUTHORIZED);
        }
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(webConfig.getJwtSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + webConfig.getJwtValidity());
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateByToken(token);
        return expiration.before(new Date());
    }

    private String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(webConfig.getJwtCookieName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    @Deprecated
    private class CustomHttpServletRequest extends HttpServletRequestWrapper {
        private Map<String, String> data;

        private CustomHttpServletRequest(HttpServletRequest request, Map<String, ?> claims) {
            super(request);
            this.data = new HashMap<>();
            claims.forEach((k, v) -> this.data.put(k, String.valueOf(v)));
        }

        @Override
        public String getHeader(String name) {
            if (data != null && data.containsKey(name)) {
                return data.get(name);
            }
            return super.getHeader(name);
        }

        @Override
        public Enumeration<String> getHeaders(String name) {
            if (data != null && data.containsKey(name)) {
                return Collections.enumeration(Collections.singletonList(data.get(name)));
            }
            return super.getHeaders(name);
        }

    }
}